/**
 * 网络请求封装
 * @module Request
 */
import * as appConfig from '@/config/config'
import * as base from '@/common/sju.base.js'
import * as nav from '@/common/sju.nav.js'
import * as alert from '@/common/sju.alert.js'
import * as login from '@/common/sju.login.js'
// 默认配置
import { t } from '@/common/sju.i18n.js'

// 响应状态码
const RESPONSE_CODE = {
  SUCCESS: 200,
  UNAUTHORIZED: 401,
  SERVER_ERROR: 500
}

// 错误消息映射
const ERROR_MESSAGES = {
  NETWORK_ERROR: t('common.request.network_error'),
  TIMEOUT_ERROR: t('common.request.timeout_error'),
  DEFAULT_ERROR: t('common.request.default_error')
}

/**
 * 网络请求
 * @param {string} url 请求地址
 * @param {string} [method='get'] 请求方法
 * @param {object} [data={}] 请求参数
 * @param {boolean} [showLoading=false] 是否显示加载框
 * @param {string} [contentType='application/x-www-form-urlencoded'] 内容类型
 * @returns {Promise}
 */
async function request(url, method = 'get', data = {}, showLoading = false, contentType = 'application/x-www-form-urlencoded') {
  try {
    showLoading && alert.showLoading()
    
    const response = await uni.request({
      method,
      timeout: appConfig.timeout,
      url: appConfig.apiUrl + url,
      data,
      header: {
        'content-type': contentType,
        'Authorization': `Bearer ${login.getValue('token')}`
      }
    })

    showLoading && uni.hideLoading()
    
    const { code = RESPONSE_CODE.SUCCESS, message } = response.data

    switch (code) {
      case RESPONSE_CODE.UNAUTHORIZED:
        await handleUnauthorized()
        throw new Error(t('common.request.unauthorized'))
      case RESPONSE_CODE.SERVER_ERROR:
        alert.showInfo(message)
        throw new Error(t('common.request.server_error'))
      case RESPONSE_CODE.SUCCESS:
        return response.data
      default:
        alert.showInfo(message)
        throw new Error(message || t('common.request.request_fail'))
    }
  } catch (error) {
    showLoading && uni.hideLoading()
    const message = parseErrorMessage(error.message)
    alert.showInfo(message)
    throw error
  }
}

/**
 * 处理未授权情况
 */
async function handleUnauthorized() {
  const res = await alert.showConfirmPromise(t('request.unauthorized_prompt'))
  if (res) {
    nav.redirectTo('/intake/login')
  }
}

/**
 * 解析错误消息
 * @param {string} message 
 * @returns {string}
 */
function parseErrorMessage(message) {
  if (message.includes('Network Error')) {
    return ERROR_MESSAGES.NETWORK_ERROR
  }
  if (message.includes('timeout')) {
    return ERROR_MESSAGES.TIMEOUT_ERROR
  }
  if (message.includes('Request failed with status code')) {
    return `${ERROR_MESSAGES.DEFAULT_ERROR} ${message.substr(message.length - 3)}`
  }
  return message || ERROR_MESSAGES.DEFAULT_ERROR
}

export { request }
